package com.cet.spring_batch_study.jobs.sftp;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.integration.sftp.session.SftpRemoteFileTemplate;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@Component
@StepScope
public class SftpDownloadTasklet implements Tasklet {

    private final SftpRemoteFileTemplate template;

    public SftpDownloadTasklet(SftpRemoteFileTemplate template) {
        this.template = template;
    }

    // 这里取 job 参数
    @Value("#{jobParameters['run.date']}")
    private String runDate;

    // 这里取配置
    @Value("${sftp.remote-dir}")
    private String remoteDir;

    @Value("${sftp.local-dir}")
    private Resource localDir;

    // 配置里拆成 prefix/suffix
    @Value("${sftp.filename-prefix:recon_}")
    private String filenamePrefix;

    @Value("${sftp.filename-suffix:.csv}")
    private String filenameSuffix;

    // 本地调试关掉 SFTP
    @Value("${sftp.disabled:false}")
    private boolean disabled;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

        // 真正的文件名在这里拼，这时候 job 参数已经有了
        String filename = filenamePrefix + runDate + filenameSuffix;

        Path dir = localDir.getFile().toPath();
        Files.createDirectories(dir);
        Path target = dir.resolve(filename);

        if (disabled) {
            // 不走 SFTP，拷贝类路径里的样例文件
            ClassPathResource sample = new ClassPathResource("samples/" + filename);
            try (InputStream in = sample.getInputStream()) {
                Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
            }
        } else {
            // 真 SFTP 下载
            template.execute(session -> {
                try (FileOutputStream os = new FileOutputStream(target.toFile())) {
                    session.read(remoteDir + "/" + filename, os);
                    return null;
                }
            });
        }

        return RepeatStatus.FINISHED;
    }
}
